//
//  JTTopicTableViewController.m
//  百思不得姐
//
//  Created by Robin Zhang on 2017/1/5.
//  Copyright © 2017年 BeiJingWangDianJieTong. All rights reserved.
//

#import "JTTopicTableViewController.h"
#import "JTHTTPSessionManager.h"
#import "JTProgressHUD.h"
#import "JTTopic.h"
#import <MJExtension.h>
#import <UIImageView+WebCache.h>
#import "JTRefreshHeader.h"
#import "JTRefreshFooter.h"
#import "JTTopicTableViewCell.h"
#import "JTCommentViewController.h"
#import "JTNewViewController.h"

@interface JTTopicTableViewController ()

/** 所有帖子数据 */
@property (nonatomic, strong) NSMutableArray<JTTopic *> *topics;
/** 下拉刷新的提示文字 */
@property (nonatomic, weak) UILabel *label;
/** maxtime:用来加载下一页数据 */
@property (nonatomic, copy) NSString *maxtime;
/** 任务管理者 */
@property (nonatomic, strong) JTHTTPSessionManager *manager;

/** 声明这个方法的目的 : 为了能够使用点语法的智能提示 */
- (NSString *)aParam;

@end

@implementation JTTopicTableViewController

#pragma mark - 仅仅是为了消除编译器发出的警告 : type方法没有实现
- (JTTopicType)type {
    
    return 0;
}

static NSString *const JTTopicTableViewCellID = @"JTTopicTableViewCell";

#pragma mark - 懒加载
- (JTHTTPSessionManager *)manager {
    
    if (!_manager) {
        
        _manager = [JTHTTPSessionManager manager];
    }
    return _manager;
}

#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupTableView];
    
    [self setupRefresh];
    
    [self registerNotification];
}

- (void)setupTableView {
    
    [self.tableView setBackgroundColor:JTCommonBgColor];
    [self.tableView setContentInset:UIEdgeInsetsMake(64 + 35, 0, 49, 0)];
    [self.tableView setScrollIndicatorInsets:self.tableView.contentInset];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([JTTopicTableViewCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:JTTopicTableViewCellID];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    /**
     作用：若为YES，则会给状态栏添加一个轻触手势，双击这个手势可以使屏幕当前的scrollView滚动至最上方。默认是YES。
     疑点：据介绍在当前屏幕上只有一个scrollView时方可生效，但实测多个scrollView也可生效。
     */
//    [self.tableView setScrollsToTop:NO];
}

- (void)setupRefresh {
    
    [self.tableView setMj_header:[JTRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewTopics)]];
    [self.tableView.mj_header beginRefreshing];
    
    [self.tableView setMj_footer:[JTRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopics)]];
}

- (void)registerNotification {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tabBarButtonDidRepeatClick:) name:JTTabBarButtonDidRepeatClickNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(titleButtonDidRepeatClick:) name:JTTitleButtonDidRepeatClickNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(anotherVoiceDidPlay:) name:JTAnotherVoiceDidPlayNotification object:nil];
}

- (NSString *)aParam {
    
    if ([self.parentViewController isKindOfClass:[JTNewViewController class]]) { // 肯定是JTEssenceViewController，需要判断是否是子类
        
        return @"newlist";
    }
    else return @"list";
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 数据加载
- (void)loadNewTopics {
    
    // 取消所有请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    // 参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.aParam forKey:@"a"]; /** 【精华】还是【最新】 */
    [params setObject:@"data" forKey:@"c"];
    
    [params setObject:[NSString stringWithFormat:@"%ld", self.type] forKey:@"type"];
    
    JTWeak(self)
    [self.manager GET:JTCommonURL parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        JTLog(@"%@", responseObject);
        
        // 存储maxtime(方便用来加载下一页数据)
        [weak_self setMaxtime:responseObject[@"info"][@"maxtime"]];
        
        // 字典数组 -> 模型数组
        [weak_self setTopics:[JTTopic mj_objectArrayWithKeyValuesArray:responseObject[@"list"]]];
        
        // 刷新表格
        [weak_self.tableView reloadData];
        
        // 让[刷新控件]结束刷新
        [weak_self.tableView.mj_header endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        JTLog(@"请求失败 - %ld", error.code);
        
        [JTProgressHUD showErrorWithError:error];
        
        // 让[刷新控件]结束刷新
        [weak_self.tableView.mj_header endRefreshing];
    }];
}

// 一个请求任务被取消了(cancel)，会自动调用AFN的failure这个block
- (void)loadMoreTopics {
    
    // 取消所有请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    // 参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.aParam forKey:@"a"];
    [params setObject:@"data" forKey:@"c"];
    [params setObject:self.maxtime forKey:@"maxtime"];
    
    [params setObject:[NSString stringWithFormat:@"%ld", self.type] forKey:@"type"];
    
    JTWeak(self)
    [self.manager GET:JTCommonURL parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        JTLog(@"%@", responseObject);
        
        // 存储maxtime(方便用来加载下一页数据)
        [weak_self setMaxtime:responseObject[@"info"][@"maxtime"]];
        
        // 字典数组 -> 模型数组
        NSArray<JTTopic *> *moreTopic = [JTTopic mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        [weak_self.topics addObjectsFromArray:moreTopic];
        
        // 刷新表格
        [weak_self.tableView reloadData];
        
        // 让[刷新控件]结束刷新
        [weak_self.tableView.mj_footer endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        JTLog(@"请求失败 - %ld", error.code);
        
        [JTProgressHUD showErrorWithError:error];
        
        // 让[刷新控件]结束刷新
        [weak_self.tableView.mj_footer endRefreshing];
    }];
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.topics.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    JTTopicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:JTTopicTableViewCellID];
    [cell setTopic:self.topics[indexPath.row]];
    
    return cell;
}

#pragma mark - <UITableViewDelegate>
/** 先执行heightForRow，再执行cellForRow */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return self.topics[indexPath.row].cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    JTCommentViewController *commentController = [[JTCommentViewController alloc] init];
    [commentController setTopic:self.topics[indexPath.row]];
    [self.navigationController pushViewController:commentController animated:YES];
}

#pragma mark - 监听
/**
 监听tabBarButton的重复点击
 */
- (void)tabBarButtonDidRepeatClick:(NSNotification *)notification {
    
    if (!self.view.window) return; // 判断当前的视图控制器的view有没有添加在window上
    if (![self.view jt_intersectWithOtherView:[UIWindow jt_highestVisibleWindow]]) return; // 判断当前的视图控制器的view与window有没有重叠
    
    JTLog(@"%@", self.class);
    
    [self.tableView.mj_header beginRefreshing];
}

/**
 监听标题按钮的重复点击
 */
- (void)titleButtonDidRepeatClick:(NSNotification *)notification {
    
    [self tabBarButtonDidRepeatClick:notification];
}

/**
 停止所有音频的播放
 */
- (void)anotherVoiceDidPlay:(NSNotification *)notification {
    
    if (self.type == JTTopicTypeAll || self.type == JTTopicTypeVoice) {
        
        if (self.topics) {
            
            [self.topics makeObjectsPerformSelector:@selector(pauseVoicePlay)];
            [self.tableView reloadData];
        }
    }
}

@end
